------------------------------------------------------------------------------------------------------------------------------------------------
-- -- tasks base lib
local function language_change_say(theNPC)
    theNPC.CHAT_TABLE = {}
    pcall(function()
        -- theNPC.npc_base_lib:Get_Language() == "ch"
        theNPC.CHAT_TABLE = TUNING.NPC_CHAT_TABLE[ theNPC.npc_base_lib:Get_Language() ] ["npc_event_woodlegs_surrounding_tent"] or {}
    end)
end

-------------------------------------------------------------------------------------------------------------------------------------------------
local actions = {
    { play = "emote_swoon" ,push = "idle_loop"},
    { play = "emoteXL_pre_dance0" , push = "emoteXL_loop_dance0" },
    { play = "emote_strikepose" ,  },
    { play = "emoteXL_happycheer" ,},
    { play = "emoteXL_kiss" ,},
    { play = "emote_pre_toast" , push = "emote_loop_toast" },
    { play = "emote_pre_toast" , push = "emote_loop_toast" },
    { play = "emote_pre_toast" , push = "emote_loop_toast" },
    { play = "emote_pre_toast" , push = "emote_loop_toast" },
    { play = "emote_pre_toast" , push = "emote_loop_toast" },
    { play = "emote_pre_toast" , push = "emote_loop_toast" },
    { play = "emote_pre_toast" , push = "emote_loop_toast" },
    { play = "emote_pre_toast" , push = "emote_loop_toast" },
    { play = "emote_pre_toast" , push = "emote_loop_toast" },
    { play = "emote_pre_toast" , push = "emote_loop_toast" },
    { play = "emote_pre_toast" , push = "emote_loop_toast" },
    { play = "emote_pre_toast" , push = "emote_loop_toast" },
    { play = "emote_pre_sit2" , push = "emote_loop_sit2" },
    { play = "research" },
    { play = "emoteXL_waving3" },
    { play = "emote_sleepy" },
    { play = "emoteXL_facepalm" },
}
local function DoActions(theNPC)
    local ret = theNPC.npc_base_lib:GetRandom(actions)
    if ret.push == nil then
        ret.push = "idle_loop"
    end
    theNPC.sg:AddStateTag("6666")
    theNPC.AnimState:PlayAnimation(ret.play)
    theNPC.AnimState:PushAnimation(ret.push)
    theNPC:DoTaskInTime(4,function()
        theNPC.sg:RemoveStateTag("6666")  
    end)
end

local function upgrade_npc_sg(theNPC)
    theNPC.sg.GoToState___old = theNPC.sg.GoToState
    theNPC.sg.GoToState = function(self,statename,...)
        if (statename == "hit" or statename == "talk") and self:HasStateTag("6666") then
            self:RemoveStateTag("6666")
        end
        if self:HasStateTag("6666") then
            return
        end
        self:GoToState___old(statename,...)
    end
end
local function NPC_TASKS_INIT(inst)
    local theNPC = inst.entity:GetParent()
    language_change_say(theNPC)
    -- Time_Out_Leave(inst)    
    -- theNPC.npc_base_lib:Equip_Random_Hat()
    -- theNPC.npc_base_lib:Equip_Random_Cloth()
    -- theNPC.npc_base_lib:Equip_Random_Weapon()
    -- theNPC:AddTag("INLIMBO")
    -- theNPC:AddTag("Unable_To_Refuse")
    upgrade_npc_sg(theNPC)

    theNPC.npc_event = inst.prefab
end

local function NPC_TASKS(inst)
    local theNPC = inst.entity:GetParent()
    if TheWorld.state.isnight  or TheWorld:HasTag("cave") then
        theNPC.npc_base_lib:Try_2_Set_Light(true)
    else
        theNPC.npc_base_lib:Try_2_Set_Light(false)
    end
    local theplayer = theNPC.__link_player
    if theplayer == nil or theplayer:IsValid() == false then
        ------ 拆营地的时候重新连接 Woodlegs 和 tent
        theplayer = TheSim:FindFirstEntityWithTag("npc_item_woodlegs_tent")
        if theplayer then
            theNPC:PushEvent("player_link",theplayer)
            theplayer.Surrounding_Woodlegs = theNPC
        else
            inst:Remove()
            theNPC:Remove()
            return
        end

    end

    ----------- 帐篷正在被带走，绕着帐篷跑就行了
    if theplayer.npc_base_lib:Get_Owner(true) then
        theNPC.npc_base_lib:Run_Around_Target_In_Range({range = 5,random_range_flag = true ,mid_reflash_range = 3 })
        -- local temp_pt = Vector3(theNPC.Transform:GetWorldPosition())
        return
    end
    ----------------------------------------------------------------------------------------------------------------------

    ----------------------------------------------------------------------------------------------------------------------
    if theNPC.event_step == nil or theNPC.event_step == 0 then
        theNPC.event_step = 0
        if theNPC:IsNearPlayer(4) == false then
            theNPC.npc_base_lib:Run_Around_Target_In_Range({range = 5,random_range_flag = true ,mid_reflash_range = 3 ,fn = function(theNPC) theNPC.event_step = 2 end})

            if theNPC.npc_base_lib:StackCheck(2,10) then
                theNPC.npc_base_lib:Run_Around_Target_In_Range({clean = true})
                theNPC.event_step = 1
            end
            if TheWorld.state.isnight then
                theNPC.event_step = 5 --- go to sleep
            end
        end
    elseif theNPC.event_step == 1 then
        -------- 卡住了，返回tent
        if theNPC.npc_base_lib:Close_2_Target_In_Range({range = 2}) then
            theNPC.event_step = 0
        end
        if TheWorld.state.isnight then
            theNPC.npc_base_lib:Run_Around_Target_In_Range({clean = true})
            theNPC.event_step = 5 --- go to sleep
        end
    elseif theNPC.event_step == 2 then
        if theNPC.npc_everything_data:Add("wait time 00",1) >= 5 then
            theNPC.npc_everything_data:Set("wait time 00",0)
            local temp_player = theNPC:GetNearestPlayer()
            if temp_player then
                theNPC.npc_base_lib:FaceToInst(temp_player)
            end
            DoActions(theNPC)
            theNPC.event_step = 3
        end      
    elseif theNPC.event_step == 3 then
        -------- 循环 surround
        if theNPC.npc_everything_data:Add("wait time 01",1) >= 20 then
            theNPC.npc_everything_data:Set("wait time 01",0)
            theNPC.event_step = 0
        end

    elseif theNPC.event_step == 5 then  ------- go to tent
        if theNPC.npc_base_lib:Distance_Targets(theNPC,theplayer) > 20 then
            theNPC.Transform:SetPosition(theplayer.Transform:GetWorldPosition())
        end
        if not TheWorld.state.isnight then ----- 如果被卡住直到白天
            theNPC.npc_base_lib:Run_Around_Target_In_Range({clean = true})
            theNPC.event_step = 0 
            return
        end
        if theNPC.npc_base_lib:Close_2_Target_In_Range({range = 2}) then
            theNPC.event_step = 6
            theplayer:PushEvent("npc_sleep")
            theNPC:Hide()
            theplayer:AddTag("INLIMBO")
        end        
    elseif theNPC.event_step == 6 then  ------- sleeping
        local pt = Vector3(theplayer.Transform:GetWorldPosition())
        theNPC.Transform:SetPosition(pt.x,30,pt.z)
        if not TheWorld.state.isnight and theNPC.npc_everything_data:Add("waking_up_timer",1) > 10 then
            theNPC.npc_everything_data:Set("waking_up_timer",0)
            theNPC.event_step = 7 --- go to wakeup
            theNPC.Transform:SetPosition(pt.x+1,0,pt.z+1)
            theNPC:Show()
            theNPC.sg:GoToState("wakeup")
            theplayer:PushEvent("npc_wakeup")
            theplayer:RemoveTag("INLIMBO")
        end
    elseif theNPC.event_step == 7 then --- waking up  --- 正在起床
        if theNPC.npc_everything_data:Add("wait time 02",1) >= 20 then
            theNPC.npc_everything_data:Set("wait time 02",0)
            theNPC.event_step = 0
        end
    end
end
--------------------------------------------------------------------------------------------------------------------------------------------------

local function OnAttached(inst,target) -- when the debuff on or player is newSpawn(or through the cave)
    inst.entity:SetParent(target.entity)
    inst.Network:SetClassifiedTarget(target)
    local NPC = inst.entity:GetParent()
    local flag ,error_code= pcall(function(inst,target)
        if TheWorld.ismastersim then

            NPC_TASKS_INIT(inst)


        end
    end,inst,target)
    if flag == false  then
        print("Error : OnAttached(inst,target) ",inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function OnDetached(inst) -- When eliminating from the outside
    local player = inst.entity:GetParent()   
    -- print(" FROM OUSIDE REMOVE ")
    
    -- inst:Remove()
end

local function ExtendDebuff(inst)
    -- inst.countdown = 3 + (inst._level:value() < CONTROL_LEVEL and EXTEND_TICKS or math.floor(TUNING.STALKER_MINDCONTROL_DURATION / FRAMES + .5))
end



local function OnUpdate(inst,ismastersim)
    local NPC = inst.entity:GetParent()
    local flag,error_code = pcall(function(inst,ismastersim)
        -- local NPC = inst.entity:GetParent()

        NPC_TASKS(inst)


    end,inst,ismastersim)
    if flag == false then
        print("Error : OnUpdate(inst,ismastersim) ,step:",NPC.event_step ,inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddNetwork()

    inst:AddTag("CLASSIFIED")


    -- inst:DoPeriodicTask(1, OnUpdate, nil, TheWorld.ismastersim)  -- in one seconds
    inst:DoPeriodicTask( 0.5, OnUpdate, nil, TheWorld.ismastersim)  -- in 0.5 seconds

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("debuff")
    inst.components.debuff:SetAttachedFn(OnAttached)
    inst.components.debuff.keepondespawn = false -- 是否保持debuff 到下次登陆
    -- inst.components.debuff:SetDetachedFn(inst.Remove)
    inst.components.debuff:SetDetachedFn(OnDetached)
    -- inst.components.debuff:SetExtendedFn(ExtendDebuff)
    -- ExtendDebuff(inst)


    return inst
end

return Prefab("npc_event_woodlegs_surrounding_tent", fn)
